import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import '../../../common/api/index.dart';
import '../../../common/models/index.dart';

class ActiviteHistoryController extends GetxController {
  // ==================== 响应式状态 ====================
  
  /// 用户ID
  final userId = 0.obs;
  
  /// 用户名
  final userName = ''.obs;
  
  /// 选择的日期
  final selectedDate = Rxn<DateTime>();
  
  /// 历史记录列表
  final RxList<UserHistoryItemEntity> historyItems = <UserHistoryItemEntity>[].obs;
  
  /// 加载状态
  final isLoading = true.obs;
  
  /// 错误消息
  final errorMessage = ''.obs;
  
  // ==================== 生命周期 ====================
  
  @override
  void onInit() {
    super.onInit();
    _handleRouteArguments();
  }
  
  @override
  void onReady() {
    super.onReady();
    _initData();
  }
  
  // ==================== 路由参数处理 ====================
  
  /// 处理路由参数
  void _handleRouteArguments() {
    debugPrint('📋 =============== 历史记录页面加载 ===============');
    
    final args = Get.arguments as Map<String, dynamic>?;
    debugPrint('📦 接收参数: $args');
    
    userId.value = args?['userId'] as int? ?? 0;
    userName.value = args?['userName'] as String? ?? '';
    
    // 默认选择今天
    selectedDate.value = DateTime.now();
    
    debugPrint('👤 用户ID: ${userId.value}');
    debugPrint('👤 用户名: ${userName.value}');
    debugPrint('📅 默认日期: ${_formatDate(selectedDate.value!)}');
  }
  
  // ==================== 数据加载 ====================
  
  /// 初始化数据
  Future<void> _initData() async {
    await loadHistoryData();
  }
  
  /// 加载历史数据
  Future<void> loadHistoryData() async {
    try {
      if (userId.value == 0) {
        errorMessage.value = '用户信息不完整';
        isLoading.value = false;
        return;
      }
      
      final date = _formatDate(selectedDate.value ?? DateTime.now());
      debugPrint('🔄 开始加载历史数据，日期: $date');
      
      isLoading.value = true;
      errorMessage.value = '';
      
      // 调用历史记录接口
      final response = await ActivityApi.getUserHistory(
        userId: userId.value,
        date: date,
        type: 'all',
      );
      
      debugPrint('✅ 历史数据加载成功: ${response.isSuccess}');
      
      if (response.isSuccess) {
        historyItems.value = response.data;
        debugPrint('📊 共加载 ${response.data.length} 条历史记录');
      } else {
        errorMessage.value = response.message ?? '加载失败';
        Get.snackbar('错误', errorMessage.value, snackPosition: SnackPosition.BOTTOM);
      }
    } catch (e) {
      debugPrint('❌ 历史数据加载失败: $e');
      errorMessage.value = '加载失败，请稍后重试';
      historyItems.value = [];
      Get.snackbar('错误', '加载失败: ${e.toString()}', snackPosition: SnackPosition.BOTTOM);
    } finally {
      isLoading.value = false;
    }
  }
  
  // ==================== 日期选择 ====================
  
  /// 显示日期选择器
  Future<void> showDatePicker() async {
    debugPrint('📅 显示日期选择器');
    
    final picked = await Get.dialog<DateTime>(
      DatePickerDialog(
        initialDate: selectedDate.value ?? DateTime.now(),
        firstDate: DateTime(2020),
        lastDate: DateTime.now(),
      ),
    );
    
    if (picked != null && picked != selectedDate.value) {
      updateSelectedDate(picked);
    }
  }
  
  /// 更新选择的日期
  void updateSelectedDate(DateTime newDate) {
    debugPrint('📅 更新选择的日期: ${_formatDate(newDate)}');
    selectedDate.value = newDate;
    loadHistoryData();
  }
  
  /// 刷新数据
  Future<void> onRefresh() async {
    debugPrint('🔄 刷新数据');
    await loadHistoryData();
  }
  
  // ==================== 工具方法 ====================
  
  /// 格式化日期为 YYYY-MM-DD
  String _formatDate(DateTime date) {
    return DateFormat('yyyy-MM-dd').format(date);
  }
  
  /// 获取格式化的日期显示
  String get formattedDate {
    if (selectedDate.value == null) {
      return _formatDate(DateTime.now());
    }
    return _formatDate(selectedDate.value!);
  }
}
